package YAVMM::HostStatDB::Plugin::MongoDB;
use Moose::Role;

use MooseX::Method::Signatures;

use TryCatch;
use Dancer ':moose';

use YAVMM::HostStat;

our $VERSION = '0.01';

with 'YAVMM::Role::MongoDB';

method add_stat (YAVMM::HostStat $stat) {
    if (not $self->_coll->insert($stat->pack)) {
	my $err  = $self->_db->last_error();
	my $estr = $err->{err} ||= '';
	die YAVMM::Error::DBError->new(
	    error => "Unable to add stat: $estr",
	);
    }
}

method get_stats (Str $host, Int $limit = 10) {
    my $cursor = $self->_coll->query(
	{ name => $host },
	{ sort_by => { 'timestamp' => -1 },
	  limit   => $limit,
      }
    );

    if (not $cursor) {
	my $err = $self->_db->last_error();
        my $estr = $err->{err} ||= '';
        die YAVMM::Error::DBError->new(
            error => "Unable to get hosts: $estr",
        );
    }

    my @stats = ();
    while (my $rec = $cursor->next) {
	push @stats, $self->_host_from_record($rec);
    }

    return @stats;
}

method _host_from_record (HashRef $obj) {
    return YAVMM::HostStat->unpack($obj);
}

1;
__END__
